package com.mflex.mwms.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;

import com.google.gson.reflect.TypeToken;
import com.mflex.mwms.R;
import com.mflex.mwms.adapter.JlrLabelPrintAdapter;
import com.mflex.mwms.adapter.TeslaCompareDetailAdapter;
import com.mflex.mwms.model.CustomApiResult;
import com.mflex.mwms.model.JLPalletLabelRequest;
import com.mflex.mwms.model.PrintqueueEntity;
import com.mflex.mwms.model.StockInfo;
import com.mflex.mwms.model.Task;
import com.mflex.mwms.model.TaskDetail;
import com.mflex.mwms.model.TeslaComapreInfo;
import com.mflex.mwms.model.TeslaCustomCompareRequest;
import com.mflex.mwms.model.enumeration.StockType;
import com.mflex.mwms.utils.MMKVUtils;
import com.mflex.mwms.utils.MessageUtils;
import com.mflex.mwms.utils.XToastUtils;
import com.xuexiang.xhttp2.XHttp;
import com.xuexiang.xhttp2.callback.CallBackProxy;
import com.xuexiang.xhttp2.callback.SimpleCallBack;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xui.utils.CollectionUtils;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.widget.dialog.MiniLoadingDialog;
import com.xuexiang.xutil.common.StringUtils;
import com.xuexiang.xutil.net.JsonUtil;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class JlrLabelPrintActivity extends BaseActivity {

    @BindView(R.id.stv_TaskNo)
    EditText stvTaskNo;
    @BindView(R.id.stv_BoxNumber)
    EditText stvBoxNumber;
    @BindView(R.id.stv_scanqty)
    EditText stvScanqty;
    @BindView(R.id.button_clear)
    Button buttonClear;

    @BindView(R.id.button_submit)
    Button buttonSubmit;

    @BindView(R.id.lvTaskList)
    ListView lvTaskList;
    @BindView(R.id.stvPrint)
    Spinner stvPrint;

    MiniLoadingDialog mMiniLoadingDialog;

    private List<String> boxList;

    List<PrintqueueEntity> printQueueInfoList;

    private String taskNO;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jlr_label_print);
        ButterKnife.bind(this);
        mMiniLoadingDialog = WidgetUtils.getMiniLoadingDialog(this, "加载...");

        stvTaskNo.setFocusable(false);
        stvScanqty.setFocusable(false);
        stvBoxNumber.setOnKeyListener(this);
        buttonClear.setOnClickListener(this);
        buttonSubmit.setOnClickListener(this);

        boxList = new ArrayList<>();

        stvBoxNumber.postDelayed(new Runnable() {
            @Override
            public void run() {
                stvBoxNumber.requestFocus();
            }
        }, 200);


        JlrLabelPrintAdapter jlrLabelPrintAdapter = new JlrLabelPrintAdapter(JlrLabelPrintActivity.this, boxList);
        lvTaskList.setAdapter(jlrLabelPrintAdapter);

        initData();

        stvPrint.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                stvPrint.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        stvBoxNumber.requestFocus();
                    }
                },200);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
                stvPrint.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        stvBoxNumber.requestFocus();
                    }
                },200);
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.button_clear:
                clearButtonMd(view);
                break;
            case R.id.button_submit:
                SubmitButtonMd(view);
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onKey(View view, int i, KeyEvent keyEvent) {
        if (keyEvent.getAction() == KeyEvent.ACTION_DOWN && (i == 66 || i == 61)) {
            switch (view.getId()) {
                case R.id.stv_BoxNumber:
                    checkBoxNumber(view);
                    break;
                default:
                    break;
            }
        }
        return false;
    }

    private void checkBoxNumber(View view) {
        if (StringUtils.isEmpty(stvBoxNumber.getText().toString())) {
            return;
        }
        if(boxList.contains(stvBoxNumber.getText().toString())){
            stvBoxNumber.setText("");
            stvBoxNumber.postDelayed(new Runnable() {
                @Override
                public void run() {
                    stvBoxNumber.requestFocus();
                }
            }, 200);
            MessageUtils.errorMsgAndVoice(JlrLabelPrintActivity.this, "此箱与已在列表中");
            return;
        }

        mMiniLoadingDialog.show();
        XHttp.get("api/Shipment/PrintJLBoxLabel")
                .params("BoxNumber", stvBoxNumber.getText().toString())
                .params("PrintQueue", stvPrint.getSelectedItem().toString())
                .params("WarehouseName", MMKVUtils.getString("Warehose", ""))
                .syncRequest(false)
                .onMainThread(true)
                .accessToken(true)
                .timeOut(120000)
                .execute(new CallBackProxy<CustomApiResult<String>, String>(new SimpleCallBack<String>() {

                    @Override
                    public void onSuccess(String response) {
                        mMiniLoadingDialog.dismiss();
                        if (StringUtils.isEmpty(taskNO)) {
                            taskNO = response;
                            stvTaskNo.setText(taskNO);
                        } else {
                            if (StringUtils.isEmpty(response)) {

                            } else {
                                if (!StringUtils.equals(response, taskNO)) {
                                    stvBoxNumber.setText("");
                                    stvBoxNumber.postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            stvBoxNumber.requestFocus();
                                        }
                                    }, 200);
                                    MessageUtils.errorMsgAndVoice(JlrLabelPrintActivity.this, "此箱与已扫箱不属于同一个出货任务");
                                    return;
                                }
                            }
                        }



                        boxList.add(stvBoxNumber.getText().toString());
                        stvBoxNumber.setText("");
                        stvBoxNumber.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                stvBoxNumber.requestFocus();
                            }
                        }, 200);
                        JlrLabelPrintAdapter jlrLabelPrintAdapter = new JlrLabelPrintAdapter(JlrLabelPrintActivity.this, boxList);
                        lvTaskList.setAdapter(jlrLabelPrintAdapter);

                        stvScanqty.setText(String.valueOf(boxList.size()));

                    }

                    @Override
                    public void onError(ApiException e) {
                        mMiniLoadingDialog.dismiss();
                        MessageUtils.errorMsgAndVoice(JlrLabelPrintActivity.this, e);
                        stvBoxNumber.setText("");
                        stvBoxNumber.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                stvBoxNumber.requestFocus();
                            }
                        }, 200);
                    }
                }) {
                });
    }


    private void clearButtonMd(View v) {
        stvBoxNumber.setFocusable(true);
        stvBoxNumber.setFocusableInTouchMode(true);
        stvBoxNumber.setText("");
        stvScanqty.setText("");
        boxList = new ArrayList<>();
        JlrLabelPrintAdapter jlrLabelPrintAdapter = new JlrLabelPrintAdapter(JlrLabelPrintActivity.this, boxList);
        lvTaskList.setAdapter(jlrLabelPrintAdapter);
        XToastUtils.success("重置成功！");
    }

    private void SubmitButtonMd(View view) {
        if (CollectionUtils.isEmpty(boxList)) {
            MessageUtils.errorMsgAndVoice(JlrLabelPrintActivity.this, "箱列表为空");
            stvBoxNumber.requestFocus();
            return;
        }
        JLPalletLabelRequest request = new JLPalletLabelRequest();
        request.setWarehouseName(MMKVUtils.getString("Warehose", ""));
        request.setBoxList(boxList);
        request.setPrintQueue(stvPrint.getSelectedItem().toString());
        mMiniLoadingDialog.show();
        XHttp.post("api/Shipment/PrintJLPalletLabel")
                .upJson(JsonUtil.toJson(request))
                .syncRequest(false)
                .onMainThread(true)
                .accessToken(true)
                .timeOut(120000)
                .execute(new CallBackProxy<CustomApiResult<String>, String>(new SimpleCallBack<String>() {

                    @Override
                    public void onSuccess(String response) {
                        mMiniLoadingDialog.dismiss();
                        XToastUtils.success("栈板签打印成功", 2500);

                        stvBoxNumber.setFocusable(true);
                        stvBoxNumber.setFocusableInTouchMode(true);
                        stvBoxNumber.setText("");
                        stvScanqty.setText("");
                        boxList = new ArrayList<>();
                        JlrLabelPrintAdapter jlrLabelPrintAdapter = new JlrLabelPrintAdapter(JlrLabelPrintActivity.this, boxList);
                        lvTaskList.setAdapter(jlrLabelPrintAdapter);
                    }

                    @Override
                    public void onError(ApiException e) {
                        mMiniLoadingDialog.dismiss();
                        MessageUtils.errorMsgAndVoice(JlrLabelPrintActivity.this, e);
                    }
                }) {
                });
    }

    private void initData(){
        mMiniLoadingDialog.show();
        XHttp.get("api/Shipment/GetJLRBoxPrintQueue")
                .params("WarehouseName", MMKVUtils.getString("Warehose", ""))
                .syncRequest(false)
                .onMainThread(true)
                .accessToken(true)
                .timeOut(120000)
                .execute(new SimpleCallBack<List<PrintqueueEntity>>() {
                    @Override
                    public void onSuccess(List<PrintqueueEntity> response) {

                        mMiniLoadingDialog.dismiss();
                        printQueueInfoList = response;

                        List<String> printList = new ArrayList<>();
                        for(PrintqueueEntity printQueueInfo : printQueueInfoList){
                            printList.add(printQueueInfo.getF_FullName());
                        }

                        String[] locationArr = printList.toArray(new String[0]);
                        WidgetUtils.initSpinnerStyle(stvPrint, locationArr);

                    }

                    @Override
                    public void onError(ApiException e) {
                        mMiniLoadingDialog.dismiss();
                        MessageUtils.errorMsgAndVoice(JlrLabelPrintActivity.this, e);
                    }
                });
    }

}